import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import path from 'path'
import { readFileSync } from 'fs'
import viteCompression from 'vite-plugin-compression'
import typescript from '@rollup/plugin-typescript'
import libCss from 'vite-plugin-libcss'
// https://vitejs.dev/config/
/**
 * 获取绝对路径
 * @param str
 */
const resolve = (str: string) => {
  return path.resolve(__dirname, str)
}
/**
 *  读取文件
 */
const packageJson = JSON.parse(
  readFileSync('./package.json', { encoding: 'utf-8' })
)
/**
 *  全局变量
 */
const globals = {
  ...(packageJson?.dependencies || {})
}
export default defineConfig({
  plugins: [
    react(),
    libCss(),
    typescript({
      target: 'es5',
      rootDir: resolve('packages/'),
      declaration: true,
      declarationDir: resolve('dist'),
      exclude: resolve('node_modules/**'),
      allowSyntheticDefaultImports: true
    }),
    viteCompression({
      verbose: true,
      disable: false,
      threshold: 10240,
      algorithm: 'gzip',
      ext: '.gz'
    })
  ],
  build: {
    cssCodeSplit: true,
    outDir: 'dist',
    lib: {
      // 组件库源码的入口文件
      entry: resolve('packages/index.tsx'),
      // 组件库名称
      name: 'demo-design',
      // 文件名称, 打包结果举例: zoom-design.cjs
      fileName: 'zoom-design',
      // 打包格式
      formats: ['es', 'cjs']
    },
    rollupOptions: {
      //排除不相关的依赖
      external: ['react',
        'react-dom',
        'antd',
        'react/jsx-runtime',
        ...Object.keys(globals)]
    }
  }
})
